<template>
  <div
    v-over="{
            topOverStart: openHzh,
            topInto: openHzh,
        }"
    v-loading="flag.videoInit === 'init'"
    class="mabox all-full yx-center"
  >
    <div
      v-show="playData"
      ref="videoBox"
      class="video full-width yx-start al-str"
    ></div>
    <div
      v-show="!playData"
      class="all-full"
    >没有资源</div>
  </div>
</template>

<script>
import { getPlayInfoByResourceId, lastPlayedTime } from "./resources";
import { VueComponents } from "./resources";
import { Promise } from "q";

let playerInstance;
const definitionMap = {
  FD: "流畅",
  LD: "标清",
  SD: "高清",
  HD: "超清",
  AUTO: "自适应"
};
export default {
  components: {},
  mixins: [VueComponents],
  props: {
    playData: {
      type: Object,
      require: true
    },
    noSeek: {
      type: Boolean,
      default: false
    },
    needRecords: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      definitions: ["LD", "SD", "HD", "AUTO"],
      definition: "LD",
      authData: null,
      timeData: {
        nowTime: 0,
        nowMaxTime: 0,
        startTime: 0
      },
      status: "init",
      lastRecords: {},
      flag: {
        auth: false,
        hzh: false,
        videoInit: "init"
      },
      video: null,
      noQp: true
    };
  },
  computed: {
    urlData () {
      if (!this.authData) return null;
      return this.authData.playInfoList.playInfo.find(
        (v) => v.definition === this.definition
      );
    },
    url () {
      return this.urlData && this.urlData.playURL;
    },
    cover () {
      if (!this.authData) return null;
      return this.authData.videoBase.coverURL;
    },
    maxSeek () {
      return Math.max(
        this.timeData.nowMaxTime,
        this.lastRecords.watchLastTime || 0
      );
    },
    lastTime () {
      return this.lastRecords.watchLastTime || 0;
    }
  },
  watch: {
    playData () {
      this.pushRecords();
      this.timeData = {
        startTime: null,
        nowTime: 0,
        nowMaxTime: 0
      };
      this.auth();
    },
    "flag.videoInit" (status) {
      if (status === "loadedmetadata") {
        this.video.currentTime = this.lastRecords.watchLastTime || 0;
        this.timeData.startTime = this.lastRecords.watchLastTime || 0;
        this.video.play();
      }
    }
  },
  mounted () {
    window.addEventListener("beforeunload", this.pushRecords);
    this.auth();
  },
  beforeDestroy () {
    this.pushRecords();
    this.video && this.$refs.videoBox.removeChild(this.video);
    window.removeEventListener("beforeunload", (e) => this.pushRecords);
  },
  activated () {
  },
  methods: {
    auth () {
      if (!this.playData || !this.playData.resourceId || this.flag.auth)
        return;
      const p = [
        getPlayInfoByResourceId({
          resourceId: this.playData.resourceId,
          definition: this.definitions.join(",")
        })
      ];
      // if (this.needRecords) {
      //     p.push(
      //         lastPlayedTime({
      //             resourceId: this.playData.resourceId,
      //             courseId: this.playData.courseId
      //         })
      //     );
      // }
      this.flagPromise(
        Promise.all(p).then(([authData, lastRecords]) => {
          this.lastRecords = lastRecords || {};
          this.authData = authData;
        }),
        "auth"
      ).then(() => {
        this.alipayer();
      });
    },
    alipayer () {
      const createVideo = (url) => {
        if (this.video) {
          this.video.src = url;
          return this.video;
        }
        const dom = this.$refs.videoBox;
        const video = document.createElement("video");
        this.video = video;
        video.className = "all-full";
        video.controls = "controls";
        video.setAttribute("controlslist", "nodownload");
        video.src = url;
        dom.appendChild(video);
        video.addEventListener("loadstart", () => {
          console.log("loadstart");
          this.flag.videoInit = "loadstart";
        });
        video.addEventListener("loadedmetadata", () => {
          console.log("loadedmetadata");
          setTimeout(() => {
            this.flag.videoInit = "loadedmetadata";
          }, 500);
        });
        if (!this.needRecords) return;
        video.addEventListener("play", this.addEL("play"));
        video.addEventListener("pause", this.addEL("pause"));
        video.addEventListener("ended", this.addEL("ended"));
        video.addEventListener("seeking", this.addEL("seeking"));
        video.addEventListener("seeked", this.addEL("seeked"));
        video.addEventListener("timeupdate", this.timeupdate);
        return video;
      };
      if (!this.url) return;
      const video = createVideo(this.url);
    },
    timeupdate () {
      const lastNowTime = this.timeData.nowTime;
      const currentTime = this.video.currentTime;
      if (this.noSeek) {
        // 禁止拖动
        if (
          currentTime - lastNowTime > 1 &&
          currentTime > this.maxSeek
        ) {
          this.video.currentTime = lastNowTime;
          return;
        }
        this.timeData.nowTime = this.video.currentTime;
        this.timeData.nowMaxTime = Math.max(
          this.timeData.nowMaxTime,
          this.timeData.nowTime
        );
      }
    },
    pushRecords () {
      if (this.noSeek) {
        this.noSeekPushRecords();
      } else if (!this.noSeek) {
        this.seekPushRecords();
      }
    },
    noSeekPushRecords () {
      const startTime = parseInt(this.timeData.startTime);
      const endTime = parseInt(this.timeData.nowTime);
      const key = startTime + "-" + endTime;
      if (startTime === "NaN" || endTime === "NaN") {
        return;
      }
      console.log("key1:", key);
      if (
        (this.pushKeys && this.pushKeys.includes(key)) ||
        endTime - startTime < 1
      ) {
        return;
      }
      this.pushKeys.push(key);
      const data = {
        courseId: this.playData.courseId,
        watchStartTime: endTime < startTime ? 0 : startTime,
        watchLastTime: endTime,
        resourceId: this.playData.resourceId
      };
      let fd = new FormData();
      for (let key in data) {
        fd.append(key, data[key]);
      }
      navigator.sendBeacon(
        "/api/course/leaning/situation/watch-history",
        fd
      );
    },
    seekPushRecords (endTime) {
    },
    addEL (emit) {
      return (event) => {
        const currentTime = this.video.currentTime;
        console.log("emit:", emit, " time:", currentTime);
        if (emit === "play") {
          this.flag.videoInit = "playing";
          this.timeData.startTime = currentTime;
          this.pushKeys = [];
        } else if (emit === "pause") {
          this.flag.videoInit = "stop";
          this.pushRecords();
        } else if (emit === "seeking") {
          this.flag.videoInit = "seeking";
        }
        this.$emit(emit, event);
      };
    },
    async openHzh () {
      // const video = this.video;
      // if (!video || this.flag.hzh) return;
      // this.flag.hzh = true;
      // try {
      //     if (video !== document.pictureInPictureElement) {
      //         // 尝试进入画中画模式
      //         await video.requestPictureInPicture();
      //     } else {
      //         // 退出画中画
      //         await document.exitPictureInPicture();
      //     }
      // } catch (error) {
      //     console.error("&gt; 出错了！", error);
      // } finally {
      //     this.flag.hzh = false;
      // }
    }
  }
};
</script>

<style lang="scss" scoped>
.mabox {
  background-color: black;
  .video {
    max-height: 100%;
  }
}
</style>
